﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using HelpCentral.Shared.Interfaces;
using HelpCentral.Data.Model;
using HelpCentral.Configuration;

namespace HelpCentral.Data.Repository
{
    class AuditRepository : IAuditRepository
    {
        HelpCentralModelContainer context = ContextContainer.Instance;

        #region IAuditRepository Members

        public IEnumerable<IAuditEvent> FetchAllAuditEvents()
        {
            return context.AuditEvents.AsEnumerable().Select(x => x.FromRepositoryObject());
        }

        public IEnumerable<IAuditEvent> FetchAuditEventsForObject(Shared.Enums.AuditEventType[] type, int? affectedObjectId)
        {
            IEnumerable<string> types = type.Select(x => x.ToString());

            return context.AuditEvents.Where(x => types.Contains(x.EventType) && (affectedObjectId == null || x.AffectedObjectId == affectedObjectId || x.SecondAffectedObjectId == affectedObjectId)).AsEnumerable().Select(x => x.FromRepositoryObject());
        }

        public IAuditEvent CommitAuditEvent(IAuditEvent auditEvent)
        {
            //var ae = context.AuditEvents.FirstOrDefault(x => x.AuditId == auditEvent.AuditId);
            var ae = auditEvent.ToRepositoryObject(context);

            if (ae == null)
            {
                ae = new AuditEvent();
            }

            if (ae.EntityState == System.Data.EntityState.Detached)
            {
                context.AuditEvents.AddObject(ae);
            }

            context.SaveChanges();

            return ae.FromRepositoryObject();
        }

        #endregion
    }
}
